import '../App.css'
import { NavBar } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import { Tabs } from 'antd-mobile'
import { useState, useEffect } from 'react'
import { orderList } from '../api/index.ts'
import { path } from '../config/index.ts'

export default function Quanbu() {
    const [data, setOrderList] = useState([]);
    const [activeKey, setActiveKey] = useState('1');
    const navigate = useNavigate();
    const userId = localStorage.getItem('uid');

    useEffect(() => {
        const fetchOrderData = async () => {
            try {
                const res = await orderList({ id: userId });
                console.log('接口返回:', res.data);
                setOrderList(res.data);
            } catch (error) {
                console.error('订单列表接口请求失败:', error);
            }
        };

        fetchOrderData();
    }, [userId]);

    const back = () => {
        navigate(-1);
    };

    // 根据状态码获取对应的状态文字
    const getStatusText = (status) => {
        switch (status) {
            case 1:
                return '待付款';
            case 2:
                return '待收货';
            case 3:
                return '已完成';
            case 4:
                return '已取消';
            default:
                return '';
        }
    };

    // 根据选项卡key筛选订单
    const getFilteredOrders = () => {
        if (activeKey === '1') {
            return data;
        } else {
            const statusMap = {
                '2': 1,
                '3': 2,
                '4': 3,
                '5': 4,
            };
            const targetStatus = statusMap[activeKey];
            return data.filter(item => item.state === targetStatus);
        }
    };

    const filteredOrders = getFilteredOrders();

    return (
        <div>
            <NavBar onBack={back}>全部订单</NavBar>
            <div className='white'>
                <Tabs
                    style={{
                        '--title-font-size': '13px',
                    }}
                    activeKey={activeKey}
                    onChange={(key) => setActiveKey(key)}
                >
                    <Tabs.Tab title='全部' key='1' />
                    <Tabs.Tab title='待付款' key='2' />
                    <Tabs.Tab title='待收货' key='3' />
                    <Tabs.Tab title='已完成' key='4' />
                    <Tabs.Tab title='已取消' key='5' />
                </Tabs>
            </div>

            {/* 订单列表或无数据提示 */}
            {filteredOrders.length > 0 ? (
                <div>
                    {filteredOrders.map((order, orderIndex) => (
                        <div className="order-item white" key={orderIndex}>
                            <div className="order-number">订单编号：{order.order}</div>
                            {order.commodity.map((product, productIndex) => (
                                <div className="product-info" key={productIndex}>
                                    <img src={path + product.image} alt={product.title} className="product-image" />
                                    <div className="product-desc">
                                        <div className="product-name">{product.title}</div>
                                        <div className="product-status">{getStatusText(order.state)}</div>
                                    </div>
                                </div>
                            ))}
                            <div className="price-and-buttons">
                                <div className="price">应付：￥{
                                    order.commodity.reduce((total, product) => {
                                        return total + parseFloat(product.price) * parseInt(product.num);
                                    }, 0).toFixed(2)
                                }</div>
                                {order.state === 1 && (
                                    <div className="buttons">
                                        <button className="cancel-btn">取消订单</button>
                                        <button className="pay-btn">付款</button>
                                    </div>
                                )}
                            </div>
                        </div>
                    ))}
                </div>
            ) : (
                // 无数据时显示的内容
                <div className="no-data-container white">
                    <p className="no-data-text">暂无相关订单</p>
                </div>
            )}
        </div>
    )
}
